layui.define(["plusConfig", "plusRouter", "plusUtil"], function (exports) {
  "use strict";

  var $ = layui.jquery,
    layer = layui.layer,
    config = layui.plusConfig,
    plusRouter = layui.plusRouter,
    plusUtil = layui.plusUtil;

  var layoutDom = ".plus-admin-layout";
  var tabDOM = layoutDom + ">.plus-admin-body>.layui-tab";
  var menuDom = layoutDom + ">.plus-admin-menu";
  var subMenuDom = layoutDom + ">.plus-admin-submenu";
  var fixedDom = subMenuDom + ">.plus-admin-submenu-fixed";
  var panelDom = layoutDom + ">.plus-admin-panel";
  var drawerDom = panelDom + ">.plus-admin-panel-drawer";
  var titleDom = layoutDom + ">.plus-admin-body>.plus-admin-body-header";
  var headerDom = layoutDom + ">.plus-admin-header";
  var thisTabDom =
    layoutDom +
    ">.plus-admin-body .layui-tab-content .layui-tab-item.layui-show";
  var copyrightDom = ".plus-admin-copyright";

  var plus = {
    resizeTable: function (time) {
      setTimeout(
        function () {
          var tbView = config.pageTabs
            ? $(
                tabDOM +
                  ">.layui-tab-content>.layui-tab-item.layui-show .plus-admin-card"
              )
            : $(layoutDom);
          tbView.find(".layui-table-view").each(function () {
            var tbId = $(this).attr("lay-id");
            layui.table && layui.table.resize(tbId);
          });
        },
        time === undefined ? 500 : time
      );
    },
    resizeTableHeight: function () {
      thisTabDom = config.pageTabs
        ?  thisTabDom:layoutDom + ">.plus-admin-body";
      function getDomHeight(d, f) {
        return d.get(0) == undefined
          ? 0
          : d.get(0).offsetHeight + (f === undefined ? 0 : f);
      }
      var headHeight = getDomHeight($(headerDom), 8);
      var h = headHeight;
      if ($(thisTabDom + " .layui-table-body") !== undefined) {
        var tabHeight = getDomHeight($(tabDOM + ">.layui-tab-title"), 16);
        var titleHeight = getDomHeight($(titleDom), 16);
        var blockHeight = getDomHeight(
          $(thisTabDom + " .plus-admin-card-tool"),
          16
        );
        var blockTabHeight = getDomHeight(
          $(thisTabDom + " .layui-tab .layui-tab-title"),
          8
        );
        var toolHeight = getDomHeight($(thisTabDom + " .layui-table-tool"));
        var thHeight = getDomHeight($(thisTabDom + " .layui-table-header"));
        var totalHeight = getDomHeight($(thisTabDom + " .layui-table-total"));
        var pageHeight = getDomHeight(
          $(thisTabDom + " .layui-table-column"),
          8
        );
        var footHeight = getDomHeight($(copyrightDom));
        // var zoom = 0;
        // if (isParent) {
        //   zoom = parent.document.getElementsByTagName("body")[0].style.zoom;
        // } else {
        //   zoom = document.getElementsByTagName("body")[0].style.zoom;
        // }
        h =
          headHeight +
          tabHeight +
          titleHeight +
          blockHeight +
          blockTabHeight +
          toolHeight +
          thHeight +
          totalHeight +
          pageHeight +
          footHeight;
        h = window.innerHeight - h;
        $(".layui-table-body").css("height", Math.ceil(h));
        // if (zoom > 1) {
        //   h = (window.innerHeight - h) / zoom;
        // } else if (zoom < 1 && zoom != "") {
        //   h = window.innerHeight / zoom - h;
        // } else {
        // h = window.innerHeight - h;
        // }
        // $(".layui-table-body").css("height", Math.ceil(h) / share);
      }
    },
    foldMenu: function () {
      var $menuDom = $(menuDom);
      var $logoDOM = $(headerDom + " .header-logo");
      var $fixedDom = $(fixedDom);
      config.topMenu
        ? $logoDOM.addClass("open").removeClass("fold")
        : $logoDOM.addClass("fold").removeClass("open");
      $menuDom.addClass("fold").removeClass("open");
      $fixedDom.addClass("open").removeClass("fold");
      $(subMenuDom).addClass("open").removeClass("fold");
      $(panelDom).addClass("fold").removeClass("open");
      $(".header-left-menu").text("➡️");
      $(drawerDom)
        .find("i")
        .addClass("layui-icon-chat")
        .removeClass("layui-icon-close");
      if ($(".plus-admin-submenu").css("display") == "none") {
        var left = config.topMenu ? 0 : 50;
        $(".plus-admin-body").css("left", left + "px");
      } else {
        var left = config.topMenu ? 110 : 160;
        $(".plus-admin-body").css("left", left + "px");
      }
      var menuRight = config.topMenu ? 0 : 160;
      var subLeft = config.topMenu ? 0 : 50;
      $(".plus-admin-body").css("right", menuRight + "px");
      $(".plus-admin-submenu").css("left", subLeft + "px");
      plus.resizeTable();
    },
    request: function (op) {
      var oldParam = plusUtil.clone(op);
      if (!op.dataType) op.dataType = "json";
      if (!op.headers) op.headers = {};
      var headers = config.getRequestHeaders(op.url);
      if (headers) {
        for (var i = 0; i < headers.length; i++) {
          if (op.headers[headers[i].name] === undefined)
            op.headers[headers[i].name] = headers[i].value;
        }
      }
      var success = op.success;
      op.success = function (result, status, xhr) {
        var before = config.getAjaxBefore(plus.parseJSON(result), op.url, {
          param: oldParam,
          reload: function (p) {
            plus.request($.extend(true, oldParam, p));
          },
          update: function (r) {
            result = r;
          },
          xhr: xhr,
        });
        if (before !== false) success && success(result, status, xhr);
        else op.cancel && op.cancel();
      };
      op.error = function (xhr, status) {
        op.success({ code: xhr.status, msg: xhr.statusText }, status, xhr);
      };
      if (
        layui.cache.version &&
        (!config.apiNoCache || op.dataType.toLowerCase() !== "json")
      ) {
        if (op.url.indexOf("?") === -1) op.url += "?v=";
        else op.url += "&v=";
        if (layui.cache.version === true) op.url += new Date().getTime();
        else op.url += layui.cache.version;
      }
      return $.ajax(op);
    },
    ajax: function (url, data, success, method, option) {
      if (typeof data === "function") {
        option = method;
        method = success;
        success = data;
        data = {};
      }
      if (method !== undefined && typeof method !== "string") {
        option = method;
        method = undefined;
      }
      if (!method) method = "GET";
      if (typeof data === "string") {
        if (!option) option = {};
        if (!option.contentType)
          option.contentType = "application/json;charset=UTF-8";
      } else if (config.putToPost) {
        if ("put" === method.toLowerCase()) {
          method = "POST";
          data._method = "PUT";
        } else if ("delete" === method.toLowerCase()) {
          method = "GET";
          data._method = "DELETE";
        }
      }
      if (
        url &&
        url.indexOf("http://") !== 0 &&
        url.indexOf("https://") !== 0 &&
        url.indexOf("//") !== 0
      ) {
        url = (config.baseServer || "") + url;
      }
      return plus.request(
        $.extend(
          {
            url: url,
            data: data,
            type: method,
            dataType: "json",
            success: success,
          },
          option
        )
      );
    },
    parseJSON: function (str) {
      if (typeof str === "string") {
        try {
          return JSON.parse(str);
        } catch (e) {}
      }
      return str;
    },
    getUndefined: function (o, t, f) {
      f = f === undefined ? o : f;
      return o === undefined ? t : f;
    },
    showLoading: function (op) {
      var elem = op.elem,
        theme = op.theme,
        type = op.type,
        opacity = op.opacity,
        size = op.size,
        text = op.text,
        loading = op.loading;
      if (type === undefined) {
        if (
          elem !== undefined &&
          typeof elem !== "string" &&
          !(elem instanceof $)
        ) {
          theme = elem.type;
          opacity = elem.opacity;
          size = elem.size;
          elem = elem.elem;
        }
        theme = plusUtil.getUndefined(theme, config.loader, 1);
        size = plusUtil.getUndefined(size, "sm");
        elem = plusUtil.getUndefined(elem, "body");
        var loader = [
          '<div class="ball-loader ' +
            size +
            '"><span></span><span></span><span></span><span></span></div>',
          '<div class="rubik-loader ' + size + '"></div>',
          '<div class="signal-loader ' +
            size +
            '"><span></span><span></span><span></span><span></span></div>',
          '<div class="layui-loader ' +
            size +
            '"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i></div>',
        ];
        var that = $(elem);
        that.addClass("page-no-scroll"); 
        that.scrollTop(0);
        var $loading = that.children(".page-loading");
        if ($loading.length <= 0) {
          that.append(
            '<div class="page-loading">' + loader[theme - 1] + "</div>"
          );
          $loading = that.children(".page-loading");
        }
        if (opacity !== undefined)
          $loading.css("background-color", "rgba(255,255,255," + opacity + ")");
        $loading.show();
      } else {
        var that = $(elem);
        if (text !== undefined && typeof text === "boolean") {
          text = undefined;
        }
        text = plusUtil.getUndefined(text, "", "加载中");
        that.addClass("plus-btn-loading");
        that.prepend(
          '<span class="plus-btn-loading-text"><i class="layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>' +
            text +
            "</span>"
        );
        that.attr("disabled", "disabled").prop("disabled", true);
      }
    },
    hideLoading: function (op) {
      var elem = op.elem,
        fade = op.fade,
        type = op.type,
        del = op.del;
      if (type === undefined) {
        elem = plusUtil.getUndefined(elem, "body");
        fade = plusUtil.getUndefined(fade, true);
        var that = $(elem);
        var $loading = that.children(".page-loading");
        if (del) $loading.remove();
        else if (fade) $loading.fadeOut("fast");
        else $loading.hide();
        that.removeClass("page-no-scroll");
      } else {
        var that = $(elem);
        that.removeClass("plus-btn-loading");
        that.children(".plus-btn-loading-text").remove();
        that.removeProp("disabled").removeAttr("disabled");
      }
    },
    putTempData: function (key, value, local) {
      var tableName = local ? config.cacheName : config.cacheName + "_tempData";
      if (value === undefined || value === null) {
        if (local) layui.data(tableName, { key: key, remove: true });
        else layui.sessionData(tableName, { key: key, remove: true });
      } else {
        if (local) layui.data(tableName, { key: key, value: value });
        else layui.sessionData(tableName, { key: key, value: value });
      }
    },
    getTempData: function (key, local) {
      if (typeof key === "boolean") {
        local = key;
        key = undefined;
      }
      var tableName = local ? config.cacheName : config.cacheName + "_tempData";
      var tempData = local
        ? layui.data(tableName)
        : layui.sessionData(tableName);
      if (!key) return tempData;
      return tempData ? tempData[key] : undefined;
    },
    rollPage: function (d) {
      var $tabTitle = $(tabDOM + ">.layui-tab-title");
      var left = $tabTitle.scrollLeft();
      if ("left" === d) {
        $tabTitle.animate({ scrollLeft: left - 120 }, 100);
      } else if ("auto" === d) {
        var autoLeft = 0;
        $tabTitle.children("li").each(function () {
          if ($(this).hasClass("layui-this")) return false;
          else autoLeft += $(this).outerWidth();
        });
        $tabTitle.animate({ scrollLeft: autoLeft - 120 }, 100);
      } else {
        $tabTitle.animate({ scrollLeft: left + 120 }, 100);
      }
    },
    refresh: function (url) {
      plusRouter.refresh(url);
    },
    closeThisTabs: function (url) {
      plus.closeTabOperNav();
      var $title = $(tabDOM + ">.layui-tab-title");
      if (!url) {
        if ($title.find("li").first().hasClass("layui-this"))
          return layer.msg("主页不能关闭");
        $title.find("li.layui-this").find(".layui-tab-close").trigger("click");
      } else {
        if (url === $title.find("li").first().attr("lay-id"))
          return layer.msg("主页不能关闭");
        $title
          .find('li[lay-id="' + url + '"]')
          .find(".layui-tab-close")
          .trigger("click");
      }
    },
    closeOtherTabs: function (url) {
      if (!url) {
        $(tabDOM + ">.layui-tab-title li:gt(0):not(.layui-this)")
          .find(".layui-tab-close")
          .trigger("click");
      } else {
        $(tabDOM + ">.layui-tab-title li:gt(0)").each(function () {
          if (url !== $(this).attr("lay-id"))
            $(this).find(".layui-tab-close").trigger("click");
        });
      }
      plus.closeTabOperNav();
    },
    closeAllTabs: function () {
      $(tabDOM + ">.layui-tab-title li:gt(0)")
        .find(".layui-tab-close")
        .trigger("click");
      $(tabDOM + ">.layui-tab-title li:eq(0)").trigger("click");
      plus.closeTabOperNav();
    },
    closeTabOperNav: function () {
      $(".layui-icon-down .layui-nav .layui-nav-child").removeClass(
        "layui-show"
      );
    },
    getPageHeight: function () {
      return (
        document.documentElement.clientHeight || document.body.clientHeight
      );
    },
    getPageWidth: function () {
      return document.documentElement.clientWidth || document.body.clientWidth;
    },
    renderTpl: function (elem) {
      if (!layui.plus) layui.plus = plus;
      function parseData(data) {
        if (!data) return;
        try {
          return new Function("return " + data + ";")();
        } catch (e) {
          console.error(e + "\nlay-data: " + data);
        }
      }
      $(elem || "[plus-admin-tpl]").each(function () {
        var $this = $(this);
        var option = $(this).data();
        option.elem = $this;
        option.tpl = $this.html();
        option.url = parseData($this.attr("plus-admin-tpl"));
        option.headers = parseData(option.headers);
        option.where = parseData(option.where);
        if (option.done) {
          try {
            option.done = new Function("res", option.done);
          } catch (e) {
            console.error(e + "\nlay-data:" + option.done);
            option.done = undefined;
          }
        }
        plusUtil.render(option);
      });
    },
    initConfig: function () {
      // 重置页签
      if (config.pageTabs && config.autoRefresh == "true")
        $(tabDOM).attr("router-autoRefresh", "true");
      // 重置版权
      if (!config.copyright) $("body").addClass("has-copyright");
      if (config.topMenu) {
        $(".plus-admin-menu").hide();
        $(".header-left").hide();
        $(".plus-admin-panel").removeClass("open").addClass("fold");
      } else {
        $(".plus-admin-menu").show();
        $(".plus-admin-panel").removeClass("open").addClass("fold");
        $(".header-logo")
          .css("background-color", "#3d3b4f")
          .css("color", "#fff")
          .css("border-bottom", "1px dashed #999")
          .css("height", "40px");
      }
      plus.renderTpl();
    },
  };

  var cache = plus.getTempData(true);
  if (cache) {
    var keys = [
      "pageTabs",
      "cacheTab",
      "theme",
      "copyright",
      "autoRefresh",
    ];
    for (var i = 0; i < keys.length; i++)
      if (cache[keys[i]] !== undefined) config[keys[i]] = cache[keys[i]];
  }
  plus.initConfig(); // 初始化配置
  exports("plus", plus);
});
